import { Component, OnInit, Input } from '@angular/core';
import { Location } from '@angular/common';
import { ConfirmationService, MenuItem } from 'primeng/components/common/api';
import { PropertyService } from '../../service/property.service';
import { ProjectService } from '../../service/project.service';
import { CountryUtilsService } from '../../../shared/services/country-utils.service';
import { PropertySaleStatus, UserStatus, UserRoles } from '../../../shared/config/app-settings';
import { AttachmentUtilsService } from '../../../shared/services/attachment-utils.service';
import { UserService } from '../../../shared/services/user.service';
import { MessageUtilsService } from '../../../shared/services/message-utils.service';
import * as _ from 'lodash';
import { Observable } from 'rxjs/internal/Observable';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-property-detail-house-view',
  templateUrl: './property-detail-house-view.component.html',
  styleUrls: ['./property-detail-house-view.component.css']
})
export class PropertyDetailHouseViewComponent implements OnInit {
  @Input() id;
  @Input() debug;
  activeIndex: number = 0;
  step: MenuItem[];
  msgs: any[] = [];
  property: any = {};
  propertyList: any = {};
  saleStatus: string;
  dialogDisplay: boolean;
  newDialogDisplay: boolean;
  newBankDisplay: boolean;
  display: boolean;
  currentNotifyEntity: any = {};
  user: any = {};
  propertyLoaded: boolean;
  previewImgSrc: string;
  imgPreview = false;

  constructor(private confirmationService: ConfirmationService,
    private propertyService: PropertyService,
    private userService: UserService,
    private location: Location,
    private translate: TranslateService,
    private messageUtilsService: MessageUtilsService,
    private attachmentUtilsService:AttachmentUtilsService,
    private propertyListService: ProjectService,
    private countryUtilsService: CountryUtilsService) { }

  ngOnInit() {
    this.getCurrentUser();
     this.resetStep();
  }

  resetStep() {
    this.step = [
        {label: 'Express Interest'},
        {label: 'Buyer\'s Detail'},
        {label: 'Solicitor\'s Detail'},
    ];
  }


  fileUpload(belongToCategory, fileUploader, entity, deleteOrigin= false) {

    if(this.id === 0) {
      this.messageUtilsService.showError(this.msgs,"Please save project first before upload files");
      return;
    }
    
    const attachment = {
      entity: entity,
      belongToID: entity.id,
      belongToCategory: belongToCategory,
      files: fileUploader.files
    };
    this.attachmentUtilsService.uploadFile(attachment, deleteOrigin).subscribe(
      (res) => {
        this.messageUtilsService.showInfo(this.msgs,' Attahement update success');
        fileUploader.clear();
        entity[belongToCategory] = res.data;
      },
      (err) => {
        console.log(err);
        this.messageUtilsService.showError(this.msgs,'Operation Failed.');
      }
    );
  }

  deleteFile(attachment ,entity?) {
    this.attachmentUtilsService.deleteAttachment(attachment).subscribe(
      (res) => {
        this.messageUtilsService.showInfo(this.msgs,attachment.originalFilename + ' delete success');
        if(entity) {
          entity[attachment.belongToCategory] = res['data'];
        }
        // this.initPropertyList();
      },
      (err) => {
        console.log(err);
        this.messageUtilsService.showError(this.msgs,'Operation Failed.');
      }
    );
  }
  loadPropertyDetail(id) {
    this.propertyService.getPropertyById(id).subscribe(
      (res) => {

        this.property = res;
        this.propertyLoaded = true;
        this.enrichResponse();
        // this.propertyStatus = this.propertylist['status'] === 'active' ? true : false;
      });
  }

  goPrevStep() {
    this.activeIndex -= 1;
    this.resizeTrigger();
  }

  isExpress() {
    return this.activeIndex === 0;
  }

  isBuyer() {
    return this.activeIndex === 1;
  }

  createBuyer(user = this.currentNotifyEntity.customer) {
    return this.userService.createBuyer(user);
  }

  nextIndex() {
    this.activeIndex += 1;
    this.resizeTrigger();
  }

  goNextStep() {
    if (this.isExpress()) {
      if (this.currentNotifyEntity.id > 0) {
        this.nextIndex();
      } else {
        this.saveSalesNote(() => {
          this.nextIndex();
        });
      }
    } else if (this.isBuyer()) {
      this.createBuyer().subscribe((user) => {
        this.currentNotifyEntity.customer = user;
        this.currentNotifyEntity.customerId = user.id;
        this.nextIndex();
      }, (err) => {
        console.log(err);
        this.messageUtilsService.showError(this.msgs,'Operation Failed.');
      });
    }
  }

  finishSave(
    solicitor = this.currentNotifyEntity.solicitor,
  ) {
    this.propertyService.createSolicitor(solicitor).subscribe((user) => {
      this.currentNotifyEntity.solicitor = user;
      this.currentNotifyEntity.solicitorId = user.id;
      this.saveSalesNote(() => {
        this.newDialogDisplay = false;
        this.newBankDisplay = false;
        this.activeIndex = 0;
        this.dialogDisplay = true;
        this.messageUtilsService.showInfo(this.msgs, 'Operation Success.');
      });
    }, (err) => {
      console.log(err);
      this.messageUtilsService.showError(this.msgs,'Operation Failed.');
    });
  }

  resizeTrigger() {
    setTimeout(() => {
       window.dispatchEvent(new Event('resize'));
     });
  }

  onSwitchChange(evt, parentKey, key) {
    this.currentNotifyEntity[parentKey][key] = !!evt.checked;
  }

  checkBankInfo() {
    this.updateUser().subscribe((res) => {
      this.user = res.data;
      if (!this.currentNotifyEntity.id) {
        this.saveSalesNote(() => {
          this.newBankDisplay = false;
          this.newDialogDisplay = true;
        });
      } else {
        this.newBankDisplay = false;
        this.newDialogDisplay = true;
      }
    }, (err) => {
      console.log(err);
      this.messageUtilsService.showError(this.msgs,'Operation Failed.');
    });
  }

  saveSalesNote(callback?: Function) {
    if (this.currentNotifyEntity.id > 0) {
        // update
        this.updateSaleNotification().subscribe(res => {
          this.messageUtilsService.showInfo(this.msgs, 'Operation Success.');
          this.loadPropertyDetail(this.id);
          this.display = false;
          console.log(res);
          callback && callback(res);
        });
    } else {
      this.createSaleNotification().subscribe(res => {
        this.messageUtilsService.showInfo(this.msgs, 'Operation Success.');
        this.loadPropertyDetail(this.id);
        this.display = false;
        console.log(res);
        callback && callback(res);
      });


    }

  }

  createSaleNotification(): Observable<any> {
     // create
     const postBody = {
      propertyId: this.property.id,
      propertyListId: this.propertyList.id,
      agentId: this.user.id,
      saleNotificationContent: this.currentNotifyEntity.saleNotificationContent
    };
    return this.propertyService.createSaleNotification(postBody);
  }

  updateSaleNotification(): Observable<any> {
     // update
     const postBody = {
      id: this.currentNotifyEntity.id,
      propertyId: this.property.id,
      propertyListId: this.propertyList.id,
      agentId: this.user.id,
      saleNotificationContent: this.currentNotifyEntity.saleNotificationContent,
      customer: this.currentNotifyEntity.customerId ? this.currentNotifyEntity.customer : null,
      customerId: this.currentNotifyEntity.customerId || null,
      solicitor: this.currentNotifyEntity.solicitorId ? this.currentNotifyEntity.solicitor : null,
      solicitorId: this.currentNotifyEntity.solicitorId || null,
    };

    return this.propertyService.updateSaleNotification(postBody);
  }

  closeNotify(msg?: string){
    this.confirmationService.confirm({
      message: this.translate.instant(msg || 'The information will be lost if you close this window directly.Are you sure that you want to perform this action?'),
      accept: () => {
        this.newDialogDisplay = false;
      }
  });
    
  }

  // utils
  enrichResponse() {
    this.propertyList = this.property.propertyList || {};
    this.property.saleNotificationList = this.property.saleNotificationList || [];
    this.currentNotifyEntity = _.find(this.property.salesNotificationList, (notification) => notification['agentId'] === this.user.id)  || {};
    this.currentNotifyEntity.customer = this.currentNotifyEntity.customer || {};
    this.currentNotifyEntity.solicitor = this.currentNotifyEntity.solicitor || {};
    this.fetchCustomerInfo();
    console.log('current notification {}', this.currentNotifyEntity);
    this.propertyService.escapeAll(this.property, false);
  }

  fetchCustomerInfo(
    id = this.currentNotifyEntity.id,
  ) {
    this.propertyService.getCustomerInfo(id).subscribe(
      (res) => {
        const {
          customerId,
          customer,
          solicitorId,
          solicitor,
        } = res;
        this.currentNotifyEntity.customer = customerId ? customer : this.currentNotifyEntity.customer;
        this.currentNotifyEntity.solicitor = solicitorId ? solicitor : this.currentNotifyEntity.solicitor;
      });
  }

  getParentProject() {
    return this.property.propertyList || {};
  }

  getPurchaseDate() {
    return this.property.purchaseDate ? new Date(this.property.purchaseDate) : null;
  }

  getCommenceDate() {
    return this.property.commenceDate ? new Date(this.property.commenceDate) : null;
  }

  getPictures() {
    const mainImages = this.property['property_main_image'] || [];
    return mainImages.length ? mainImages : [{filePath: '/assets/img/no_photo_property.png'}];
  }

  getFullName(user) {
    return user ? this.userService.getFullName(user) : 'Nobody';
  }

  newNotifySale() {
    console.log('DEBUG: newNotifySale');
    // 已绑定银行账户
    if (this.user.bankName || /^c/.test(this.user.code)) {
      if (this.currentNotifyEntity.id > 0) {
        this.newDialogDisplay = true;
      } else {
        this.createSaleNotification().subscribe(res => {
          console.log('create first,{}', res);
          this.currentNotifyEntity = res.data;
          this.currentNotifyEntity.customer = this.currentNotifyEntity.customer || {};
          this.currentNotifyEntity.solicitor = this.currentNotifyEntity.solicitor || {};
          this.newDialogDisplay = true;
        });
      }
    // 未绑定银行账户
    } else {
      this.newBankDisplay = true;
    }
  }

  notifySale() {
    // if (Number(this.debug) === 1) {
      this.newNotifySale();
    // } else {
    //   if(this.currentNotifyEntity.id > 0){
    //     this.display = true;
    //   }else{
    //     this.createSaleNotification().subscribe(res=>{
    //       console.log("create first,{}",res);
    //       this.currentNotifyEntity = res.data;
    //       this.display = true;
    //     });
    //   }
    // }
  }

  isSaleNotesEmpty() {
    return _.isEmpty(this.property.sale_note) ? true : false;
  }

  isBankCardEmpty() {
    return _.isEmpty(this.property['property_bank_card_picture']);
  }


  getCurrentUser() {
    this.userService.getCurrentUser().subscribe((user) => {
      this.user = user;
      this.loadPropertyDetail(this.id);
    }, () => {
      this.loadPropertyDetail(this.id);
    });
  }

  updateUser(user = this.user): Observable<any> {
    return this.userService.updateUser(user);
  }

  isPropertyAvailableForUser(property) {
    if ((!property.agentId && property.sale_status === PropertySaleStatus.FOR_SALE) || this.user.id === property.agentId || property.sale_status === PropertySaleStatus.FOR_SALE || this.user.role === UserRoles.ADMIN) {
      return true;
    }
    return false;

  }

  openLargeImage(imgSrc) {
    this.previewImgSrc = imgSrc.filePath;
    this.imgPreview = true;
  }

  back() {
    this.location.back();
  }
}
